<template>
  <div class="container">
    <div class="app-container">
      <el-button
        class="btn-add"
        size="mini"
        type="primary"
        @click="showDialog = true"
      >添加权限</el-button>
      <el-table
        default-expand-all
        :data="list"
        row-key="id"
        :props="defaultProps"
      >
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button v-show="row.type === 1 && row.pid === 0" size="mini" type="text" @click="addPermissionSecond(row.id)">添加</el-button>
            <el-button size="mini" type="text" @click="editPermission(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="deletePermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 放置弹层组件 -->
    <add-permission ref="addPermission" :current-node-id="currentNodeId" :show-dialog.sync="showDialog" @updatePermission="getPermissionList" />
  </div>
</template>
<script>
import { getPermissionList, deletePermission } from '@/api/permission'
import AddPermission from './components/add-permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Permission',
  components: { AddPermission },
  data() {
    return {
      currentNodeId: null, // 存储当前点击的id
      showDialog: false, // 控制弹层显示和隐藏
      list: [],
      defaultProps: {
        label: 'name', // 要显示的字段名字
        children: 'children' // 读取子节点的字段名
      }
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      const result = await getPermissionList()
      this.list = transListToTreeData(result, 0)
    },
    addPermissionSecond(id) {
      this.currentNodeId = id
      this.showDialog = true
    },
    editPermission(id) {
      this.currentNodeId = id
      this.showDialog = true
      this.$nextTick(() => { this.$refs.addPermission.getPermissionDetail() })
      // this.$nextTick(() => { this.$refs.addPermission.getPermissionDetail() })
    },
    deletePermission(id) {
      this.$confirm('您确认删除该权限吗').then(async() => {
        await deletePermission(id)
        // 提示消息
        this.$message.success('删除权限成功')
        this.getPermissionList()
      })
    }
  }
}
</script>
<style>
.btn-add {
  margin: 10px;
}
</style>
